package com.wk.code.wkserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wk.code.wkserver.constant.NumberConstant;
import com.wk.code.wkserver.entity.UserAccount;
import com.wk.code.wkserver.mapper.UserAccountMapper;
import com.wk.code.wkserver.service.IUserAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * <p>
 * 用户账户余额表 服务实现类
 * </p>
 *
 * @author wq
 * @since 2021-08-15
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements IUserAccountService {

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void createUserAccount(Integer userId) {
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userId);
        userAccount.setBalance(BigDecimal.ZERO);
        save(userAccount);

    }

    @Override
    public void increaseBalance(Integer techUserId, BigDecimal techAccount) {
        UserAccount userAccount = baseMapper.selectOne(new LambdaQueryWrapper<UserAccount>().
                eq(UserAccount::getUserId, techUserId));
        if (Objects.nonNull(userAccount)) {
            userAccount.setBalance(userAccount.getBalance().add(techAccount));
            updateById(userAccount);
        }
    }

    @Override
    public void decreaseBalance(Integer techUserId, BigDecimal techAccount) {
        UserAccount userAccount = baseMapper.selectOne(new LambdaQueryWrapper<UserAccount>().
                eq(UserAccount::getUserId, techUserId));
        if (Objects.nonNull(userAccount)) {
            userAccount.setBalance(userAccount.getBalance().subtract(techAccount));
            updateById(userAccount);
        }
    }

    @Override
    public UserAccount selectUserAccount(Integer userId) {
        return baseMapper.selectOne(new LambdaQueryWrapper<UserAccount>().eq(UserAccount::getUserId, userId));
    }
}
